<!DOCTYPE HTML>
<html lang="en">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="JS中的异步“承诺”——Promise, Casey Lu&#39;s Blog">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>JS中的异步“承诺”——Promise | Casey Lu&#39;s Blog</title>
    <link rel="icon" type="image/png" href="/medias/maozhao.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>
    
<meta name="generator" content="Hexo 4.2.0"><link rel="alternate" href="/atom.xml" title="Casey Lu's Blog" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>


<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">Casey Lu's Blog</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>Index</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>Tags</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>Categories</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>Archives</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>About</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="Search" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">Casey Lu's Blog</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			Index
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			Tags
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			Categories
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			Archives
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			About
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    
<script src="/libs/cryptojs/crypto-js.min.js"></script>
<script>
    (function() {
        let pwd = '';
        if (pwd && pwd.length > 0) {
            if (pwd !== CryptoJS.SHA256(prompt('嘻嘻嘻，访问本文章需要密码')).toString(CryptoJS.enc.Hex)) {
                alert('密码错误哦~');
                location.href = '/';
            }
        }
    })();
</script>




<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/articleimages/5.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">JS中的异步“承诺”——Promise</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/Javascript/">
                                <span class="chip bg-color">Javascript</span>
                            </a>
                        
                            <a href="/tags/ES6/">
                                <span class="chip bg-color">ES6</span>
                            </a>
                        
                            <a href="/tags/Promise/">
                                <span class="chip bg-color">Promise</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                技术分享
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>Publish Date:&nbsp;&nbsp;
                    2020-03-01
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>Word Count:&nbsp;&nbsp;
                    1.5k
                </div>
                

                

                
            </div>

        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>最近在复习JS的知识，其中JS中的异步是最频繁被提及的，决定结合现阶段的学习来简单地梳理一下个人理解<img class="emoji" draggable="false" alt="💭" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4ad.png"/>。</p>
<p>JS 是一种典型的单线程语言，这是由它在浏览器上运行的性质所决定的。若在并行的线程中实现，并行的线程上无法实现对DOM的修改，此外发生重定向到另一个URL是非常危险的。这时候就有一个不容小觑的问题，JS在单线程上运行时，尤其是处理向服务器发出请求这种较慢的进程时，会使得浏览器处于漫长的等待响应中而被锁定<img class="emoji" draggable="false" alt="🔒" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f512.png"/></p>
<p><strong>解决这种问题的方式就是————异步</strong></p>
<p>在js中，实现异步的方式主要有两种<img class="emoji" draggable="false" alt="💕" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f495.png"/><strong>一是回调函数，二是Promise实现</strong>（ES6及之后）</p>
<h2 id="一、使用回调函数实现异步">一、使用回调函数实现异步</h2>
<p>使用回调函数callback处理的时候，callback作为参数传递给任何异步函数，来告知在结果准备好时调用另一个函数。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">    doSomethingAsync(callback);    // doSometingAsync接收回调函数作为参数（只传递引用，几乎无开销） 
    console.log('complete');
    
    // 当doSomethingAsync完成时，回调
    function callback(error => {
       if(!error)
           console.log('doSomethingAsync finished');
    });
</code></pre>
<p><img class="emoji" draggable="false" alt="✔️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2714.png"/>Terminal 的结果是：</p>
<pre class=" language-language-powershell"><code class="language-language-powershell">complete
doSomethingAsync finished
</code></pre>
<p>当我们想串行执行几个异步任务的时候，往往会想到使用嵌套回调函数来实现。事实上，当我们在js中使用大量异步回调时，容易造成“<a href="http://callbackhell.com/" target="_blank" rel="noopener">回调地狱</a>”问题，使得错误处理逻辑混乱并且代码阅读困难。<strong>解决回调地狱，可以使用Promise +Generator + Async / Await</strong></p>
<h2 id="二、使用ES6中的Promise实现异步">二、使用ES6中的Promise实现异步</h2>
<p>单从字面意义出发，我想理解为Promise就是JavaScript对于用户请求的数据返回承诺。Promise不仅是实现异步，还可以解决因为大量回调串行造成的回调地狱。在ES6中依旧可以使用回调，但是Promise提供了更加去清洗的语法chains异步命令，因此可以串行运行。</p>
<p><strong>Promise的三种状态：</strong> pending（等待） 、resolved/fulfilled（已完成） 、rejected(已拒绝)。状态的转换只可以是pending → fulfilled / rejected</p>
<p><strong>Promise构造函数的两个参数：</strong></p>
<ul>
<li>resolve： 处理成功之完成之后运行的回调函数 pending → fulfilled</li>
<li>reject：发生故障时运行的可选回调函数 pending → rejected<br>
两者都可以传入任意类型的值作为实参，表示Promise对象成功/失败的值</li>
</ul>
<p><strong>Promise常用的三种方法有：</strong></p>
<ul>
<li>then——异步执行成功之后的数据状态变为 resolve</li>
<li>catch——异步执行失败之后的数据状态变为reject</li>
<li>all——多个没有关系的 Promise 封装成为一个 Promise对象,使用then返回一个数组数据</li>
<li>ES2018引入了.finally方法，无论如何都会运行的逻辑，目前仅支持Chrome和Firebox</li>
</ul>
<p><strong>1. then方法——顺序的异步</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">promise.then(onFulfilled, onRejected); // 均为可选参数
</code></pre>
<p>异步链 Promise Chains 的实现</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">promise.then(onFulfilled1, onRejected1).then(onFulfilled2,onRejected2);
</code></pre>
<p>举个<img class="emoji" draggable="false" alt="🌰" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f330.png"/>（两个Promise实现3s后打印）</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">let promiseA = new Promise((reslove,reject) => {
    setTimeout(() => {
      resolve('success')
    }, 1000)
})
promiseB = promiseA.then(res => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve('PromiseB 中返回一个Promise对象')
      },2000)
    })
})
promiseB.then(res => {
    console.log(res)  // 3s之后打印“PromiseB ... ” 
})
</code></pre>
<p>再举个坏<img class="emoji" draggable="false" alt="🌰" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f330.png"/>（抛异常）：</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">const db = require('dataset')

//connect to the database
function asyncDBconnect(param){
    return new Promise((resolve, reject) => {
      db.connect(param, (err, connection) => {
        if(err)
          reject(err); //连接失败,处理异常
        else
          resolve(connection);
      });
    });
}

</code></pre>
<p>数据库API提供一个接收回调函数的connect()方法;<br>
外部的asyncDBcontent()函数立刻返回一个新的Promise,并在简历之前的连接或者失败之后运行resolve或者reject<br>
<strong>2.all 方法——多个异步调用，同时启动，无关顺序</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Promise.all([async1, async2, async3])
    .then(values => {
      console.log(values);
      return values;
    })
    .catch(err => {
      console.log('error',err);
    })
</code></pre>
<p>在上述例子中，接收一组函数并且返回另外一个Promise，在all中的所有异步操作结束之后才能回调。<br>
特点：如果任何一个异步函数调用失败，则Promise.all()立即终止<br>
<strong>3.race 方法——多个异步调用，仅最快的Promise才能完成</strong><br>
与all()类似，race()也是多个异步的调用，但是不同的是他会在第一个Promise对象 resolve或者reject 之后立即执行回调（解析或拒绝），不用等待全部的Promise 执行完成。</p>
<pre class=" language-language-javascript"><code class="language-language-javascript">Promise.race([async1, async2, async3])
    .then(value => {
      console.log(value);
      return value;
    })
    .catch(err => {
      console.log('error', err);
    })
</code></pre>
<p>除了上述三种之外, reject()、 catch()的用法也就不做过多的赘述。值得一提的是，当Promise 状态变为rejected的时候会被reject()、catch()捕捉到，而当.catch()前面已经设置了reject的回调函数，.catch()不会捕捉到状态变为rejected的情况。catch还可以捕捉到在resolve 或者  reject 中发生的错误。</p>
<p>Promise还可以在回调函数中使用return 和 throw, 所以在then 中可以return 出一个Promise对象或者其他值，也可以throw一个错误对象，但是如果没有return,将默认返回undefined, 那么后面的then中的回调函数接收到的也将是undefined.</p>
<p>本文主要讲Promise之后，会继续写关于使用Generator 和 Async/Await 解决回调地狱~ 敬请期待hhhhh</p>
<p><img class="emoji" draggable="false" alt="⭐️" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/2b50.png"/>最后，附上最近看到的一道题：<img class="emoji" draggable="false" alt="📝" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4dd.png"/><strong>如何实现sleep的效果？</strong><br>
<strong>1、while循环的方式</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function sleep(time){
  var start = Date.now();
  while(Date.now() < start +time){};
  console.log('sleep-1,休眠结束！');
  return;
}
</code></pre>
<p>缺点： 容易造成死循环<br>
<strong>2、Promise的方式</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function sleep(time){
  var temp = new Promise( (reslove) = > {
    console.log('sleep2-1')
    setTimeout(resolve, time)
  });
  return temp;
}
sleep(500).then(function(){
  console.log('sleep2-2') // 延迟500ms输出
})
</code></pre>
<p><strong>3、async封装的方式</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function sleep(time){
  return new Promise((resolve) => {
    setTimeout(resolve,time)
  });
}
async function test(){
  var temp = await sleep(1000);
  console.log('sleep-3');
  return temp;
}
test(); // 延迟1000ms之后输出了‘sleep-3’
</code></pre>
<p><strong>4、generate的方式</strong></p>
<pre class=" language-language-javascript"><code class="language-language-javascript">function* sleep(time){
  yield new Promise(function(resolve,reject){
    console.log('sleep-4:1');
    setTimeout(resolve, time);
  })
}
sleep(500).next().value.then(function(){
  console.log('sleep-4:2'); //500ms之后输出
})
</code></pre>
<p>sleep写多了，cc成功地困了<img class="emoji" draggable="false" alt="💤" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f4a4.png"/>，晚安~ <img class="emoji" draggable="false" alt="😴" src="https://twemoji.maxcdn.com/v/12.1.5/72x72/1f634.png"/></p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        Author:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io" rel="external nofollow noreferrer">Casey Lu</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        Link:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://caseylu.gitee.io/2020/03/01/2-js-zhong-de-yi-bu-cheng-nuo-promise/">https://caseylu.gitee.io/2020/03/01/2-js-zhong-de-yi-bu-cheng-nuo-promise/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        Reprint policy:
                    </i>
                </span>
                <span class="reprint-info">
                    All articles in this blog are used except for special statements
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    reprint polocy. If reproduced, please indicate source
                    <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>Copied successfully, please follow the reprint policy of this article</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">more</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/Javascript/">
                                    <span class="chip bg-color">Javascript</span>
                                </a>
                            
                                <a href="/tags/ES6/">
                                    <span class="chip bg-color">ES6</span>
                                </a>
                            
                                <a href="/tags/Promise/">
                                    <span class="chip bg-color">Promise</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">谢谢大佬的小鱼干，喵~</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.jpg" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>
            
        </div>
    </div>

    
        <link rel="stylesheet" href="/libs/gitalk/gitalk.css">
<link rel="stylesheet" href="/css/my-gitalk.css">

<div class="card gitalk-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="gitalk-container" class="card-content"></div>
</div>

<script src="/libs/gitalk/gitalk.min.js"></script>
<script>
    let gitalk = new Gitalk({
        clientID: 'b739596984975414aa79',
        clientSecret: 'c5792bc3376f951910111f232176fbadfa919286',
        repo: 'L0ittle.github.io',
        owner: 'L0ittle',
        admin: "L0ittle",
        id: '2020-03-01T21-59-20',
        distractionFreeMode: false  // Facebook-like distraction free mode
    });

    gitalk.render('gitalk-container');
</script>
    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;Previous</div>
            <div class="card">
                <a href="/2020/03/03/3-qian-duan-xing-neng-de-you-hua-de-si-kao/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/24.jpg" class="responsive-img" alt="前端性能优化的思考">
                        
                        <span class="card-title">前端性能优化的思考</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            前端性能的优化一直是前端开发之中的重中之重，技术层出不穷的今日，用户对页面访问速度和响应度的要求也与日俱增。在实际的项目开发中，用户体验就是前端优化的生产力，是前端开发的终极奥义。而要探讨性能优化的时候，往往是多方面的~
首先回顾一下，有关
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2020-03-03
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E6%8A%80%E6%9C%AF%E5%88%86%E4%BA%AB/" class="post-category">
                                    技术分享
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Javascript/">
                        <span class="chip bg-color">Javascript</span>
                    </a>
                    
                    <a href="/tags/CSS/">
                        <span class="chip bg-color">CSS</span>
                    </a>
                    
                    <a href="/tags/DOM/">
                        <span class="chip bg-color">DOM</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                Next&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2020/02/29/1-wo-de-ge-ren-bo-ke-shang-xian-liao/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/articleimages/23.jpg" class="responsive-img" alt="四年一遇的日子,我的Blog上线了">
                        
                        <span class="card-title">四年一遇的日子,我的Blog上线了</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            思考了关于很多个人将来的打算，现阶段处于知识储备阶段，对于前端技术的内容虽然有了解和基础，仍然需要深度进阶。今天看了很多大牛的博客，尤其是冴羽大大的还有小伍学姐的Blog，感触很深。优秀的人总是会始终坚持着自己的习惯。
不断学习，不断进步。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2020-02-29
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E4%BA%BA%E7%94%9F%E6%9D%82%E8%B0%88/" class="post-category">
                                    人生杂谈
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Life/">
                        <span class="chip bg-color">Life</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('100')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + 'From: Casey Lu&#39;s Blog<br />'
            + 'Author: Casey Lu<br />'
            + 'Link: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;TOC</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>



    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="4892766072"
                   fixed='true'
                   autoplay='false'
                   theme:='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">2020</span>
            <a href="https://caseylu.gitee.io" target="_blank">Casey Lu</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">63.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/L0ittle" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:caseylu119@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1351238945" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1351238945" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>







    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;Search</span>
            <input type="search" id="searchInput" name="s" placeholder="Please enter a search keyword"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
